package com.baizhi.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory ssf = null;
    private static ThreadLocal<SqlSession> tl = new ThreadLocal<SqlSession>();

    static{
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            //2、创建SqlSessionFactoty工厂对象
            ssf = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    //获取链接
    public static SqlSession openSession(){
        //3、通过工厂对象获取SqlSession对象 （连接）
        SqlSession ss = tl.get();
        if(ss == null){
            ss = ssf.openSession();
            tl.set(ss);
        }
        return ss;
    }

    //获取链接  只用于缓存测试   每次调用获取的是一个新的链接
    public static SqlSession getSqlSession(){
        return ssf.openSession();
    }

    //获取DAO接口的实现类
    public static Object getMapper(Class clazz){
        return  openSession().getMapper(clazz);

    }

    //关闭资源
    public static void close(){
        openSession().close();
        tl.remove();
    }
    //事务提交
    public static void commit(){
        openSession().commit();
        close();
    }
    //事务回滚
    public static void rollback(){
        openSession().rollback();
        close();
    }
}
